package link.cocoon.security.util;

import javax.annotation.Resource;
import link.cocoon.system.entity.User;
import link.cocoon.system.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

/**
 * @author xce
 * @date 2020/1/13  12:04
 */
@Service
public class SecurityService {

  @Resource
  private UserService userService;


  /**
   * 获取当前用户的用户名.
   *
   * @return 用户名.
   */
  private String getCurrentUsername() {
    Authentication authentication = getCurrentAuthentication();
    UserDetails userDetails = (UserDetails) authentication.getPrincipal();
    return userDetails.getUsername();
  }

  public User getCurrentUser(){
    String username = getCurrentUsername();
    return userService.getByUsername(username);
  }

  private static Authentication getCurrentAuthentication() {
    return SecurityContextHolder.getContext().getAuthentication();
  }

}
